package com.reebake.ideal.servlet.config;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.reebake.ideal.servlet.core.ResponseBodyWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
@ConditionalOnProperty(prefix = "mvc.exception", name = "enable-global-handler", havingValue = "true")
public class GlobalRestExceptionHandler {

    /**
     * 异常以json格式输出
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> handleException(Exception e) {
        log.debug("error", e);
        ResponseBodyWrapper responseBodyWrapper = SpringUtil.getBean(ResponseBodyWrapper.class);
        Object result = null;
        if(ObjUtil.isNull(responseBodyWrapper)){
            result = e.getMessage();
        }else {
            result = responseBodyWrapper.convert(e);
        }
        return ResponseEntity.status(500).body(result);
    }

}
